package com.service;

import com.utils.WeixinUtil;
import com.vo.WxOpenIdVO;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class WxLoginService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${weixin.appid}")
    private  String appid;

    @Value("${weixin.secret}")
    private  String secret;




    /**
     * 获取用户openid
     * @param code
     * @return
     */
    public String wxLogin(String code,String nick,String head,String miwen,String iv)
    {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
        String newUrl = String.format(url,appid,secret, code);
        String resultString = restTemplate.getForObject(newUrl,String.class);
        WxOpenIdVO vo  = JSONObject.parseObject(resultString,WxOpenIdVO.class);

        //解密加密的用户信息
        String sessonKey = vo.getSession_key();
        String jiemi = WeixinUtil.decryptData(miwen,sessonKey,iv);

        //实际项目中，还要查数据库是否存在，如果不存在就要新增，否则更新
        System.out.println("解密后的:"+jiemi);
        System.out.println(code);
        System.out.println(nick);
        System.out.println(head);
        System.out.println(vo.getOpenid());
        return "";
    }




}
